/// <reference path="jquery-vsdoc2.js" />

/******************************************************************************
 * WSS List Object Class by Samir Sijercic and Will Lawrence  3/27/2009
 * 
 * Way to call from form view web part:
 
 <script type="text/javascript" src="jquery.js" ></script>
 <script type="text/javascript" src="jPoint.js" ></script> 
 
 <script type="text/javascript">
 try
 {
 	//Way#1: Calling the constructor
 	var myjPoint = new jPoint();
 }
 catch(e)
 {
 	alert(e.description);
 }
 </script>
 *
 ******************************************************************************/
var FieldInternalName = "FieldInternalName";
var FieldName = "FieldName";
var FieldType = "FieldType";
var jPointObj = null;
$.extend({
    includePath: '',
    include: function(file) {
        var files = typeof file == "string" ? [file]:file;
        for (var i = 0; i < files.length; i++) {
            var name = files[i].replace(/^\s|\s$/g, "");
            var att = name.split('.');
            var ext = att[att.length - 1].toLowerCase();
            var isCSS = ext == "css";
            var tag = isCSS ? "link" : "script";
            var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
            var link = (isCSS ? "href" : "src") + "='" + $.includePath + name + "'";
            if ($(tag + "[" + link + "]").length == 0) document.write("<" + tag + attr + link + "></" + tag + ">");
        }
    }
});
//Include CSS and JS
$.includePath = '/jPoint/src/'; //This will have to be modifiable since we do not know where users will keep include files
$.include(['jPointFormListItem_expanded.js', 'jPoint_debug_expanded.js']);

//Constructor
function jPoint() 
{ debugger;
	$.logfunction("jPoint() Enter Constructor");
	try
	{
		//Form initialization
		this.Form = new Object();
		this.Form.Items = new Array();
		this.Form.ItemNames = new Array();
		this.Form.FieldCount=0;
		this.Form.id = 0; //Default form ID for new form
		this.Form.AutoSaveInterval=0;
		//Sharepoint initialization
		this.SPLC = new Object();
		this.SPLC.Items = new Array();
		this.SPLC.FieldCount=0;
		//Declare Methods are declared below function definitions
		
		//Save jpoint object for jquery manipulation
		jPointObj = this;
		//Start Private functions ----
		/*
		 * name: readForm
		 * purpose: get all Sharepoint Page Form Items
		 * visibility: public
		 * fill jPoint object with form data
		 * input: none
		 * return: this.Form
		 */
		function readForm()
		{
			$.logfunction("readForm() Enter Method");
			try
			{
				var ListItem = null;
				var nextItem = 0;
				var arr = document.getElementsByTagName("!");
				if (!arr || arr.length < 2 || location.href.toLowerCase().indexOf("form.aspx") < 0) {
				    arr = getAlternativeComments();   //private function to handle special exceptions for non-IE browsers or for List Form webparts.
				}
								
				jPointObj.Form.Items = new Array();
				jPointObj.Form.ItemNames = new Array();
				jPointObj.Form.FieldCount = 0;
				$.loginfo("Array length:" + arr.length);
			   	// get all comments
			   	for (var i=0;i < arr.length; i++ )
			   	{
			   		//Get internal field name
			   		if (arr[i].innerHTML.indexOf(FieldInternalName) > 0)
					{
						//Match the field name
				      	ListItem = new jPointFormListItem(arr[i]);
									
				      	nextItem = jPointObj.Form.Items.length;
						jPointObj.Form.Items[nextItem] = ListItem;
			
				      	//Create dynamic class
				      	jPointObj.Form[ListItem.InternalName]=ListItem;
			
				      	//Used for showing to user all internal names of the Forms page
				      	jPointObj.Form.ItemNames.push("Form." + ListItem.InternalName);
				    }
			   	}
			   	//Attachements found
			   	jPointObj.Form.Attachments = new Array();
			   	if(document.getElementById("idAttachmentsRow") &&
			   	document.getElementById("idAttachmentsRow").style.display != 'none')
			   	{
			   		$("#idAttachmentsTable").find("span[dir=ltr]").each(function() {
			   			jPointObj.Form.Attachments.push(this.innerHTML);
			   		});
			   		jPointObj.Form.ItemNames.push("Form.Attachements");
			   	}
			   	//Easy way to access # of form fields loaded
				jPointObj.Form.FieldCount= jPointObj.Form.Items.length;
				$.loginfo("Form FieldCount:" + jPointObj.Form.FieldCount);   
			}
			catch(err)
			{
				$.log("readForm Error:" + err);
			}
			$.logfunction("readForm() Exit Method");
			return jPointObj.Form;

}
/*
* name: getAlternativeComments
* purpose: get all Sharepoint Page Form fields by way of a manufactured "comments" node
* visibility: private
* alternative method to find and tag (by way of inserting an equivalent "comments" node) form fields
* input: none
* return: arr - array of hidden divs that equate to the comments node for each field of a list newform.aspx page.
*/
	getAlternativeComments = function () {
    $.logfunction("readForm2() Enter Method");
    try {
        //need to find title="title" element and get its id
        var formID;
        var idLength = 20;  //needs to be long enough to ensure that it is unique on the page.
        //An id looks like ctl00_m_g_b54611a5_5bb2_4e40_bb73_e526437dd4ca_ctl00_ctl04_ctl28_ctl00_ctl00_ctl04_ctl00_ctl00
        var commentsObj, Listitem, comments, commentsNode; //hidden span that will equate to the comments node of a field of a list newform.aspx page
        var jPointTable, jPointRows, jPointRowID, arrayFields, arr = null;

        formID = $("*[title='Title']").get(0).id.substring(0, idLength); //from above example, this would look like ctl00_m_g_b54611a5_5
        
        //from the title row, traverse up and find the table and add class name of "jPointForm formID"
        jPointTable = $("*[title='Title']").closest("table").addClass("jPointTable").addClass(formID);

        //find and name all of the tables first set of trs and add class name of "jPointRow formID" and add id equal to label of the field which is
        //by finidng first td's innerText (textConent in firefox - so use jQuery's text()) with all special chars stripped out
        jPointRows = jPointTable.children()/*tbody*/.children()/*tr*/.addClass("jPointRow").attr("id", function(arr) {
            return $($(this).find("td").get(0).childNodes[0]/*H3 or <b>*/).text().replace(/[^a-zA-Z0-9]+/g,'');
        //below can be cut and pasted into firebug console for testing
        //$("*[title='Title']").closest("table").addClass("jPointRow").children()/*tbody*/.children()/*tr*/.addClass("jPointRow").attr("id", function(arr) {return $($(this).find("td").get(0).childNodes[0]/*H3 or <b>*/).text().replace(/[^a-zA-Z0-9]+/g,'');})
        });

        arr = $("tr.jPointRow > td:nth-child(2):visible").each( function (intIndex) {
            //construct comments
            commentsObj = {};
            jPointRowID = $(this).parent().attr("id")
            commentsObj[FieldName] = jPointRowID;
            commentsObj[FieldInternalName] = jPointRowID;  //not sure a good way to grab the internal name.  via SPLC?
            commentsObj[FieldType] = "SPColumn";            
            comments = FieldName + '="' + commentsObj.FieldName + '" ' +
                       FieldInternalName + '="' + commentsObj.FieldInternalName + '" ' +
                       FieldType + '="' + commentsObj.FieldInternalName + '" ';       
            //insert commentsNode at beginning of TD just like where Sharepoint puts its comments on the xxxxForm.aspx pages.
        	$(this).prepend("<div class='commentsNode' style='display: none'>"+comments+"</div>");
        }).find("div.commentsNode"); 


        //find all elements that start with first part of that id
        //arrayFields = $("*[id^='" + formID + "']:not([type='hidden'])");

        //find parent tr of each arrayField and add class name of "jPointRow formID"
        //jPointRows = $("tr:has(" + arrayFields + ")").addClass("jPointRow").addClass(formID);
        
    }
    catch (err) {
        $.log("readForm Error:" + err);
    }
    $.logfunction("readForm2() Exit Method");
    return arr;
}

		/*
		 * name: saveForm
		 * purpose: save currently opened form
		 * visibility: public		 
		 * input: none, on edit form make sure before call to saveForm that jPoint.Form.id is set
		 * recomendation: try saving form.id into cookie so page postbacks do not clear Form.id
		 * return: void
		 */
		function saveForm()
		{
			var today=new Date();
			$.logfunction("saveForm() Enter Method:" + today.getHours()+":"+today.getMinutes()+":"+today.getSeconds());
			try
			{
				$.loginfo("Detected:" + location.href);
			   	//Get the site url from page location property
			   	var siteURL = location.href.substr(0, location.href.indexOf("/Lists"));
			   	//Extract list name from page location property
			   	var linklistName = location.href.substr((siteURL.length + 7), location.href.substr((siteURL.length + 7)).indexOf("/"));
			   	linklistName = unescape(linklistName);
			   	var listName = linklistName;
			   	if(listName.toUpperCase() == "OPS EVENT FILLIN FROM" || listName.toUpperCase()=="OPS EVENT FILLIN FORM")
				   	listName = "Ops Event Fill-In Form"; //Redo listName
			   	if(jPointObj.Form.id == -1) //Used to call new form item from edit page
			   	{
			   		jPointObj.Form.id = 0;
			   	}
			   	else if(jPointObj.Form.mode() == "EDIT" && location.href.indexOf("ID=") > -1 && jPointObj.Form.id < 1)//Used to retrieve id on Edit Form Page
			   	{
			   		var idEnd = location.href.substr(location.href.indexOf("ID=") + 3).indexOf("&");
			   		var formID = 0;
			   		if(idEnd > -1)
			   			formID = location.href.substr(location.href.indexOf("ID=") + 3, idEnd);
			   		else
			   			formID = location.href.substr(location.href.indexOf("ID=") + 3);
			   		
			   		if(formID > 0)
			   			jPointObj.Form.id = formID;
			   	}
			   	//Read form if form fields are not read yet
				jPointObj.Form.readForm();
				//If it has detected some form fields try to process
				if(jPointObj.Form.Items.length > 0)
				{
					//Set up SPLC with site and list name
				   	var currentlistSPLC = jPointObj.SPLC.setSPObject(siteURL, listName);
					var listItem = null;
					//Start creating add new form item
				   	var saveformjSON = {};
				   	//On updates set form id to current form
				   	saveformjSON['id'] = jPointObj.Form.id;
				   	$.loginfo("Current Form id:" + jPointObj.Form.id);
				   	for (var i=0;i < jPointObj.Form.Items.length; i++ )
				   	{
				   		//Get form item
				   		listItem = jPointObj.Form.Items[i];
				   		$.loginfo("Working on:" + listItem.Type);
				   		switch(listItem.Type)
			   			{
			   				case "SPFieldDateTime":
			   					var dateobj = new Date(listItem.getValue());
				   				saveformjSON[listItem.InternalName] = dateobj.getFullYear() + "-" + (dateobj.getMonth()+1) + "-" + dateobj.getDate() + " " + dateobj.getHours() + ":" + dateobj.getMinutes() +":" + dateobj.getSeconds() + "Z";	
			   					break;
			    			case "SPFieldUser":
			    				var SPFieldUserData = listItem.getValue();
			    				$.loginfo("User field length:" + SPFieldUserData.length);
			    				if(SPFieldUserData.length > 0)
			    				{
			    					var divData = $("Div[data]", SPFieldUserData).attr("data");
				    				$.loginfo("Data attribute:" + divData);
				    				//Data attribute comes in as string so we manipulate string to pull out username and id values	
				    				var uid = '';
				    				var username = '';
				    				if(divData.indexOf("SPUserID") > -1)
				    				{
				    					uid =divData.substr(divData.indexOf("SPUserID") + 43);
				    					uid = uid.substr(0, uid.indexOf("<"));
				    					username = divData.substr(divData.indexOf("DisplayName") + 46); //+ 35
										username = username.substr(0, username.indexOf("<"));
				    				}
				    				else //Special case when users use email instead of their ID for people picker
				    				{
				    					username = divData.substr(divData.indexOf("Email") + 40);
										username = username.substr(0, username.indexOf("<"));
										username = username.substr(0, username.indexOf('@'));
										currentlistSPLC.getUserProfile("eonuser:" + username); //EON specific
										uid=currentlistSPLC.User.ID;
									}
									$.loginfo(uid + ";#" + username);
									//Format user field
				    				saveformjSON[listItem.InternalName] = uid + ";#" + username;
			    				}
			    				else
			    				{
			    					//Empty user field
			    					saveformjSON[listItem.InternalName] = SPFieldUserData;
			    				}
			    				break;
			     			default: //all other fields are not as irregular and are taken care of with below statement
						      	saveformjSON[listItem.InternalName] = listItem.getValue();
						      	break;
			     
			    		}
				   	}
				   	var itemArray = new Array;
				   	itemArray.push(saveformjSON);
				   	//id=0 add new item
				   	//id>0 update existing item
				   	//Then update Form.id for subsequent auto save
				   	jPointObj.Form.id = currentlistSPLC.addItem(itemArray).id;
				   	//update attachments
				   	currentlistSPLC.updateAttachments(jPointObj.Form.id, jPointObj.Form.Attachments);
				   	
				   	//Overwrite OK button in order to avoid update conflict
				   	var okButtons = $('input[type="button"][value="OK"]');
				   	if(okButtons.length ==0)
				   		okButtons = $('input[type="button"][value="Save"]');//Ops Specific
				   	if(okButtons.length > 0)
				   	{
				   			//Format each okButton
						   	$(okButtons).each(function() {
								var newOnclickText = 'var myJPObj=new jPoint(); jPointObj.Form.id = '+jPointObj.Form.id+';myJPObj.Form.saveForm();';
								this.onclick= new Function(newOnclickText);
							});
					}
					var cancelButtons = $('input[type="button"][value="Cancel"]');
					if(cancelButtons.length == 0)
						cancelButtons = $('input[type="button"][value="Save and Close"]'); //Ops Specific
					if(cancelButtons.length > 0)
				   	{
							//Format each cancel button
						   	$(cancelButtons).each(function() {
								var newOnclickText = 'var myJPObj=new jPoint(); jPointObj.Form.id = '+jPointObj.Form.id+';myJPObj.Form.saveForm();location.href=location.href.substr(location.href.indexOf("Source=") + 7) + "?Source=" + location.href.substr(location.href.indexOf("Source=") + 7)';
								this.onclick= new Function(newOnclickText);
							});
					}
				   	//Overwrite Attach button in order to avoid update conflict
					$('a[accesskey="I"]').each(function(){
						this.href = "https://c3.eon.faa.gov/sharepointutils/AddAttachment.aspx?dest="+ siteURL + "&lst=" + listName + "&ID=" + jPointObj.Form.id + "&q=jqmodal&width=40%&height=15%";
						$.log(this.href, 0);
						this.onclick=function(){jPointObj.Form.AutoSaveInterval=0;};
	
					});
					//Overwrite Delete button
					$('a[accesskey="X"]').each(function(){
						this.onclick=function(){
							setTimeout(function(){jPointObj.Form.deleteForm()}, 3000); //Needs a time out, if page changes href and item is deleted sharepoint throws an error
							location.href=location.href.substr(location.href.indexOf("Source=") + 7) + "?Source=" + location.href.substr(location.href.indexOf("Source=") + 7);
							
							//debugger;
						};
					});
					//Make Attach button be modal popup
					$(document).ready(function(){
						//thickbox replacement
					var closeModal = function(hash)
					{
						var $modalWindow = $(hash.w);
						$modalWindow.fadeOut('2000', function()
						{
							hash.o.remove();
							//refresh parent
							if (hash.refreshAfterClose == true)
							{
								var parentWindow = document.location.href;
								if(parentWindow.indexOf("NewForm.aspx?") > -1)//On new page after attachment is closed
								{
									parentWindow = parentWindow.replace("NewForm.aspx?", "EditForm.aspx?ID=" + jPointObj.Form.id + "&")
								}
								else //On edit page after attachment is closed
								{
									parentWindow = parentWindow.substr(0, parentWindow.indexOf("ID="))+ "ID=" + jPointObj.Form.id + parentWindow.substr(parentWindow.indexOf("ID=")).substr(parentWindow.substr(parentWindow.indexOf("ID=")).indexOf("&"));
								}
								location.href = parentWindow;
							}
						});
					};
					var openInFrame = function(hash)
					{
						var $trigger = $(hash.t);
						var $modalWindow = $(hash.w);
						var $modalContainer = $('iframe', $modalWindow);
						var myUrl = $trigger.attr('href');
						var myTitle = $trigger.attr('title');
						var newWidth = 0, newHeight = 0, newLeft = 0, newTop = 0;
						$modalContainer.html('').attr('src', myUrl);
						$('#jqmTitleText').text(myTitle);
						myUrl = (myUrl.lastIndexOf("#")> -1) ? myUrl.slice(0, myUrl.lastIndexOf("#")) : myUrl;
						var queryString = (myUrl.indexOf("?")> -1) ? myUrl.substr(myUrl.indexOf("?") + 1) : null;
						if (queryString != null && typeof queryString != 'undefined')
						{
							var queryVarsArray = queryString.split("&");
							for (var i = 0; i <queryVarsArray.length; i++)
							{
								if (unescape(queryVarsArray[i].split("=")[0]) == 'width')
								{
									var newWidth = queryVarsArray[i].split("=")[1];
								}
								if (escape(unescape(queryVarsArray[i].split("=")[0])) == 'height')
								{
									var newHeight = queryVarsArray[i].split("=")[1];
								}
								if (escape(unescape(queryVarsArray[i].split("=")[0])) == 'jqmRefresh')
								{
									hash.refreshAfterClose = queryVarsArray[i].split("=")[1]
								} else
								{
									hash.refreshAfterClose = true;
								}
							}
							// let's run through all possible values: 90%, nothing or a value in pixel
							if (newHeight != 0)
							{
								if (newHeight.indexOf('%')> -1)
								{
									newHeight = Math.floor(parseInt($(window).height()) * (parseInt(newHeight) / 100));
								}
								var newTop = Math.floor(parseInt($(window).height() - newHeight) / 2);
							}
							else
							{
								newHeight = $modalWindow.height();
							}
							if (newWidth != 0)
							{
								if (newWidth.indexOf('%')> -1)
								{
									newWidth = Math.floor(parseInt($(window).width() / 100) * parseInt(newWidth));
								}
								var newLeft = Math.floor(parseInt($(window).width() / 2) - parseInt(newWidth) / 2);
							}
							else
							{
								newWidth = $modalWindow.width();
							}
							// do the animation so that the windows stays on center of screen despite resizing
							$modalWindow.css({
								width: newWidth,
								height: newHeight,
								opacity: 0
							}).jqmShow().animate({
								width: newWidth,
								height: newHeight,
								top: 10, //newTop
								left: newLeft,
								marginLeft: 0,
								opacity: 1
							}, 'slow');
						}
						else
						{
							// don't do animations
							$modalWindow.jqmShow();
						}
					}
					//Making Attach document modal
					$('#modalWindow').jqm({
									overlay: 70,
									modal: true,
									trigger: 'a[accesskey="I"]',
									target: '#jqmContent',
									onHide: closeModal,
									onShow: openInFrame
								});
						
					});
				}
			   	else
			   	{
			   		alert("saveForm only works on the New/Edit form page.");
			   	}
			   	
			}
			catch(err)
			{
				$.log("saveForm Error:" + err);
			}
			$.logfunction("saveForm() Exit Method");
		}
		/*
		 * name: deleteForm
		 * purpose: delete currently opened SPList Item
		 * visibility: public		 
		 * input: none, on edit form make sure before call to saveForm that jPoint.Form.id is set
		 * return: void
		 */
		function deleteForm()
		{
			var today=new Date();
			$.logfunction("deleteForm() Enter Method:" + today.getHours()+":"+today.getMinutes()+":"+today.getSeconds());
			try
			{
				$.loginfo("Detected:" + location.href);
			   	//Get the site url from page location property
			   	var siteURL = location.href.substr(0, location.href.indexOf("/Lists"));
			   	//Extract list name from page location property
			   	var linklistName = location.href.substr((siteURL.length + 7), location.href.substr((siteURL.length + 7)).indexOf("/"));
			   	linklistName = unescape(linklistName);
			   	var listName = linklistName;
			   	if(listName.toUpperCase() == "OPS EVENT FILLIN FROM" || listName.toUpperCase()=="OPS EVENT FILLIN FORM")
				   	listName = "Ops Event Fill-In Form"; //Redo listName
			   	if(jPointObj.Form.id == 0)
			   	{
			   		if(jPointObj.Form.mode() == "EDIT" && location.href.indexOf("ID=") > -1 && jPointObj.Form.id < 1)//Used to retrieve id on Edit Form Page
				   	{
				   		var idEnd = location.href.substr(location.href.indexOf("ID=") + 3).indexOf("&");
				   		var formID = 0;
				   		if(idEnd > -1)
				   			formID = location.href.substr(location.href.indexOf("ID=") + 3, idEnd);
				   		else
				   			formID = location.href.substr(location.href.indexOf("ID=") + 3);
				   		
				   		if(formID > 0)
				   			jPointObj.Form.id = formID;
				   	}
			   	}
			   	if(jPointObj.Form.id == 0)
			   	{
			   		alert("Form can not be deleted!");
			   		return;
			   	}
			   	else
			   	{
			   		var currentlistSPLC = jPointObj.SPLC.setSPObject(siteURL, listName);
					currentlistSPLC.deleteItem(jPointObj.Form.id);
			   	}
			}
			catch(err)
			{
				$.log("deleteForm Error:" + err);
			}
			$.logfunction("deleteForm() Exit Method");

		}
		/*
		 * name: autoSave
		 * purpose: save currently opened form periodicaly
		 * visibility: public		 
		 * input: seconds (int), if seconds iz zero stops previously started auto save
		 * return: void
		 */
		function autoSave(seconds)
		{
			$.logfunction("autoSave() Enter Method");
			try
			{
				var seconds = seconds * 1000;
				jPointObj.Form.AutoSaveInterval = seconds;
				timedSave();
			}
			catch(err)
			{
				$.log("autoSave Error:" + err);
			}
			$.logfunction("autoSave() Exit Method");
		}
		/*
		 * name: getFormMode
		 * purpose: detects form mode (NEW / DISP / EDIT)
		 * visibility: public		 
		 * input: none
		 * return: mode (string)
		 */
		function getFormMode()
		{
			$.logfunction("getFormMode() Enter Method");
			var formMode = "";
			try
			{				
				var pname = location.pathname.toLowerCase();
				$.loginfo("Page name:" + pname);
				if (pname.indexOf("newform.aspx") > 0)
					formMode = "NEW";
				else if(pname.indexOf("dispform.aspx") > 0)
					formMode = "DISP";
				else if(pname.indexOf("editform.aspx") > 0)
					formMode = "EDIT";
			}
			catch(err)
			{
				$.log("getFormMode Error:" + err);
			}
			$.logfunction("autoSave() Exit Method with value:" + formMode);
			return formMode;
		}
		/*
		 * name:getFormItem
		 * purpose: get Item by Name
		 * visibility: public
		 * input: form field name
		 * return: Form Item object
		 */
		function getFormItem(itemName)
		{
			$.logfunction("getFormItem("+itemName+") Enter Method");
			try
			{
				$.loginfo("Form FieldCount:" + jPointObj.Form.Items.length);
				for (var i=0;i < jPointObj.Form.Items.length; i++ )
			   	{
					if(jPointObj.Form.Items[i].Name.toUpperCase() == itemName.toUpperCase())
					{
						$.loginfo("Found '"+ itemName + "'");
						$.logfunction("getFormItem() Exit Method");
						return jPointObj.Form.Items[i];
					}
			   	}
			   	//Alert user that referenced sharepoint form field is not found
			   	alert("'" + itemName + "' is not a valid sharepoint form field for the current page!");
		   	}
		   	catch(err)
		   	{
		   		$.log("getFormItem Error:" + err);	
		   	}
		}
		/*
		 * name: getFormItemNames
		 * purpose: get all Form Item Names
		 * input: none
		 * return: string
		 */
		function getFormItemNames()
		{
			$.logfunction("getFormItemNames() Method");
			var itemNames = jPointObj.Form.ItemNames.join(",\n");
			$.loginfo("getFormItemNames:'"+ itemNames + "'");
			return itemNames;
		}
		/*
		 * name: clearForm
		 * purpose: clear all Form Fields
		 * input: none
		 * return: void
		 */
		function clearForm()
		{
			$.logfunction("clearForm() Enter Method");
			try
			{
				var arr = document.getElementsByTagName("!");
				$.loginfo("number of form fields:'"+ arr.length + "'");
			    // get all comment tags
			    for (var i=0;i < arr.length; i++ )
			    {
			    	//Get all FieldInternalNames
			   		if (arr[i].innerHTML.indexOf(FieldInternalName) > 0)
					{
				      //Match the field name
				      ListItem = new jPointFormListItem(arr[i]);
				      //Clear form field value
				      ListItem.setValue('');
				    }
			     } 		
			}
			catch(err)
			{
				$.log("clearForm Error:" + err);
			}
			$.logfunction("clearForm() Exit Method");
		}
		/*
		 * name: timedSave
		 * purpose: recursivly call Form save
		 * input: seconds
		 * return: void
		 */
		function timedSave()
		{
			$.logfunction("timedSave() Method");
			if(jPointObj.Form.AutoSaveInterval > 0)
			{
				jPointObj.Form.saveForm();
				//Recursive call using closure
				setTimeout(function(){timedSave()},jPointObj.Form.AutoSaveInterval);
			}
			else
			{
				$.loginfo("Stopped auto saving form.");
			}
		}
		//SPLC functions ---
		/*
		 * name: getSPItemNames
		 * purpose: get all SPLC Item Names
		 * input: none
		 * return: string
		 */
		function getSPItemNames()
		{
			$.logfunction("getSPItemNames() Method");
			var SPLCItems = jPointObj.SPLC.Items.join(",\n");
			$.loginfo("number of form fields:'"+ SPLCItems + "'");
			return SPLCItems;
		}
		/*
		 * name: setSPObject
		 * purpose: set SPLC Item
		 * constructs SPLC[item]
		 * input: SiteURL (string), Sharepoitn List Name (string)
		 * return: none
		 */
		function setSPObject(SiteURL, ListName)
		{
			$.logfunction("setSPObject("+SiteURL+", "+ListName+") Enter Method");
			try
			{
				var sListName = ListName.toUpperCase();
				var spObj=jPointObj.SPLC[sListName]=new Object();
				//Set SPList object properties
				//Adding _vti_bin for web service sharepoint calls so user does not have to remember the entire path
				if(SiteURL.length != SiteURL.replace(/\/_vti_bin/i, "").length)
					SiteURL = SiteURL + "/";
				else if(SiteURL.length == "/")
					SiteURL = SiteURL + "/_vti_bin/";
				else
					SiteURL = SiteURL + "/_vti_bin/";
				spObj.SiteURL=SiteURL;
				spObj.ListName=ListName;
			    spObj.CamlQuery='';
			    //Set all item functions
			    spObj.getSPItem=getSPItem;
				spObj.getSPItemsWithQuery=getSPItemsWithQuery;
				spObj.getSPView=getSPView;
				spObj.updateItem=updateItem;
				spObj.addItem=addItem;
				spObj.deleteItem=deleteItem;
				spObj.getUserProfile=getUserProfile;
				spObj.updateAttachments=updateAttachments;
				spObj.getAttachments=getAttachments;
				spObj.deleteAttachment=deleteAttachment;
				$.loginfo("Set up spObj successfully");
				//SPList object functions
				/*
				 * name: getSPItem
				 * purpose: get SPListItem by ID (int)
				 * visibility: public
				 * input: unique list item ID
				 * return: void
				 */
				function getSPItem(ListItemID)
				{
					$.logfunction("getSPItem("+ListItemID+") Enter Method");
					try
					{
						//in this case 'this' is the jPoint.SPLC.ListName
						this.CamlQuery = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + ListItemID + "</Value></Eq></Where>";
						//Get Item from sharepoint
						getSPItemData(this);
						
					}
					catch(err)
				    {
				        $.log("getSPItem Error:" + err);
				    }
				    $.logfunction("getSPItem() Exit Method");
				}
				/*
				 * name: getSPItemsWithQuery
				 * purpose: get SPListItems by CAML query
				 * visibility: public
				 * input: CAML query (string), rowLimit(int)
				 * return: void
				 */
				function getSPItemsWithQuery(CamlQuery, rowLimit)
				{
					$.logfunction("getSPItemsWithQuery("+CamlQuery+", "+rowLimit+") Enter Method");
					try
					{
						this.CamlQuery=CamlQuery;
						//Get Item from sharepoint
						getSPItems(this, rowLimit);
						
					}
					catch(err)
				    {
				    	$.log("getSPItemsWithQuery Error:" + err);
				    }
				    $.logfunction("getSPItemsWithQuery() Exit Method");
				}
				/*
				 * name: getSPView
				 * purpose: populate jPoint object with items for particular view
				 * default: default view name is "All Items"
				 * visibility: public
				 * input: View Name (string)
				 * return: void
				 */
				function getSPView(ViewName)
				{
					$.logfunction("getSPView("+ViewName+") Enter Method");
					try
					{
						if(ViewName == null)ViewName='';
						this.ViewName = ViewName;
						//Get Item from sharepoint
						getSPViewItems(this);
					
					}
					catch(err)
					{
						$.log("getSPView Error:" + err);
					}
					$.logfunction("getSPView() Exit Method");
				}
				/*
				 * name: updateItem
				 * purpose: update/add SPList item
				 * visibility: public
				 * input: data (JSON object) 
				 * 		example:data to modified JSON object [{ id:0, title:'title123', user:'user123'}, {id:5, title:'title124', user:'user124'}]
				 *		if id = 0 Add item otherwise update item
				 * return: operation result
				 * 		{ success: (bool) whether the operation is success
				 * 		  errorCode: error code, 0x00000000 for no error
				 * 		  errorText: error text, null for no error
				 * 		  id: item id, -1 for error
				 * 		}
				 */
				function updateItem(data){
					$.logfunction("updateItem("+data+") Enter Method");
					//Default results
					var result = {success:false, errorCode:'', errorText:'internal error', id:-1};
					try
					{
						var listObj = this;
						//Build xml representation for update item
						var content = buildModifyContent(listObj.ListName, data);
						//Call webservice to update list item
						innerPost(listObj.SiteURL + 'lists.asmx', 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems', content, function(data){
							if ($('ErrorText', data).length > 0) {
								result.success = false;
								result.errorCode = $('ErrorCode', data).text();
								result.errorText = $('ErrorText', data).text();
								result.id = -1;
							} else {
								result.success = true;
								result.errorCode = '0x00000000';
								result.errorText = null;
								result.id = $('z\\:row', data).attr('ows_ID');
							}
						});	
					}
					catch(err)
					{
						$.log("updateItem Error:" + err);
					}
					$.loginfo("results: success:"+ result.success+",  errorCode:"+result.errorCode+", errorText:"+result.errorText+", id:"+result.id);
					$.logfunction("updateItem() Exit Method");
					return result;
				}
				/*
				 * name: addItem
				 * purpose: add a new item SPList item
				 * visibility: public
	 			 * input: data (JSON object)
				 * 		example:data to modified JSON object [{ id:0, title:'title123', user:'user123'}, {id:0, title:'title125', user:'user125'}]
				 * return: operation result
				 * 		{ success: (bool) whether the operation is success
				 * 		  errorCode: error code, 0x00000000 for no error
				 * 		  errorText: error text, null for no error
				 * 		  id: new item id, -1 for error
				 * 		}
				 */
				function addItem(data){
					$.logfunction("addItem("+data+") Method");
					//Call update item with JSON object
					return this.updateItem(data);
				}
				/*
				 * name: deleteItem
				 * purpose: delete SPList item
				 * visibility: public
				 * input: id of SPList item (int)
				 * return: operation result
				 * 		{ success: (bool) whether the operation is success
				 * 		  errorCode: error code, 0x00000000 for no error
				 * 		  errorText: error text, null for no error
				 * 		}
				 */
				function deleteItem(id)
				{
					$.logfunction("deleteItem("+id+") Enter Method");
					//Default results
					var result = {success:false, errorCode:'', errorText:'internal error'};
					try
					{
						var listObj = this;
						//Build xml representation for update item
						var content = buildDeleteContent(listObj.ListName, id);
						//Call webservice to update list item
						innerPost(listObj.SiteURL + 'lists.asmx', 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems', content, function(data){
							if ($('ErrorText', data).length > 0) {
								result.success = false;
								result.errorCode = $('ErrorCode', data).text();
								result.errorText = $('ErrorText', data).text();
							} else {
								result.success = true;
								result.errorCode = '0x00000000';
								result.errorText = null;
							}
						});
					}
					catch(err)
					{
						$.log("updateItem Error:" + err);
					}
					$.loginfo("results: success:"+ result.success+",  errorCode:"+result.errorCode+", errorText:"+result.errorText);
					$.logfunction("deleteItem() Exit Method");
					return result;

				}
				/*
				 * name: updateAttachments
				 * purpose: updateAttachments SPList item attachments
				 * visibility: public
				 * input: none, references 'this' which is SPList item
				 * return: void
				 */
				function updateAttachments(listItemID, currentAttachments)
				{
					$.logfunction("updateAttachments() Enter Method");
					//Default results
					try
					{
						var listObj = this;
						listObj.getAttachments(listItemID);
						//Build xml representation for update item
						var bDelete = true;
						for(var j=0; j< listObj.Attachments.length; j++)
						{
							bDelete = true;
							for(var i=0; i<currentAttachments.length; i++)
							{
								if($(currentAttachments[i]).attr("href") != null && listObj.Attachments[j].toUpperCase().replace(/ /g, "%20") == $(currentAttachments[i]).attr("href").toUpperCase())
								{
									bDelete= false;
									break;
								}
							}
							//Delete attachment
							if(bDelete)
							{
								listObj.deleteAttachment(listItemID, listObj.Attachments[j].toUpperCase());
							}
						}

					}
					catch(err)
					{
						$.log("updateAttachments Error:" + err);
					}
					$.logfunction("updateAttachments() Exit Method");

				}
				/*
				 * name: getAttachments
				 * purpose: getAttachments SPList item attachments
				 * visibility: public
				 * input: none, references 'this' which is SPList item
				 * return: void
				 */
				function getAttachments(listItemID)
				{
					$.logfunction("getAttachments() Enter Method");
					//Default results
					try
					{
						var listObj = this;
						//Build xml representation for update item
						innerPost(listObj.SiteURL + 'lists.asmx', 
						'http://schemas.microsoft.com/sharepoint/soap/GetAttachmentCollection',
						'<GetAttachmentCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/"><listName>' + listObj.ListName + '</listName><listItemID>' + listItemID + '</listItemID></GetAttachmentCollection>',
						function(data){
							listObj.Attachments = new Array();
							$('Attachment', data).each(function()
							{
								listObj.Attachments.push(this.firstChild.nodeValue);
							});
						});					
					}
					catch(err)
					{
						$.log("getAttachments Error:" + err);
					}
					$.logfunction("getAttachments() Exit Method");
				}
				function deleteAttachment(listItemID, attachmentURL)
				{
					$.logfunction("deleteAttachment() Enter Method");
					//Default results
					try
					{
						var listObj = this;
						//Build xml representation for update item
						innerPost(listObj.SiteURL + 'lists.asmx', 
						'http://schemas.microsoft.com/sharepoint/soap/DeleteAttachment',
						'<DeleteAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/"><listName>' + listObj.ListName + '</listName><listItemID>' + listItemID + '</listItemID><url>' + attachmentURL + '</url></DeleteAttachment>',
						function(data){
							listObj.Attachments = new Array();
							$('Attachment', data).each(function()
							{
								listObj.Attachments.push(this.firstChild.nodeValue);
							});
						});
					}
					catch(err)
					{
						$.log("deleteAttachment Error:" + err);
					}
					$.logfunction("deleteAttachment() Exit Method");

				}

				/*
				 * name: getUserProfile
				 * purpose: get user profile data
				 * visibility: public
				 * input: user name (string)
				 * return: user profile data populated in jPoint.SPLC["ListName"].User object
				 */
				function getUserProfile(userName)
				{
					$.logfunction("getUserProfile("+userName+") Enter Method");
					try
					{
						var listObj = this;
						listObj.User = new Object();
						innerPost(listObj.SiteURL + 'usergroup.asmx', 
						'http://schemas.microsoft.com/sharepoint/soap/directory/GetUserInfo',
						'<GetUserInfo xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/"><userLoginName>' + userName + '</userLoginName></GetUserInfo>',
						function(data){
							var SPItem = $(data).find('User').get(0).attributes;
							$(SPItem).log(null, 3);
							for (i=0; i<SPItem.length; i++)
							{
								listObj.User[SPItem[i].name]=SPItem[i].value;
					            jPointObj.SPLC.Items.push(SPItem[i].name);
							}
							//For easy access to SP field count returned from getSPItem call
							listObj.User.FieldCount= SPItem.length;
							$.loginfo("Number of user fields:" + listObj.User.FieldCount);
						});
					}catch(err)
					{
						$.log("Error in getUserProfile:" + err);
					}
					$.logfunction("getUserProfile() Exit Method");
				}
				/*
				 * name: getSPItemData
				 * purpose: fills jpoint.SPLC["ListName"] object with values for single SPList item
				 * visibility: private
				 * input: listObject (jPoint.SPLC["ListName"] object) 
				 * return: data populated in jPoint.SPLC["ListName"] object
				 */
				function getSPItemData(listObj)
				{
					$.logfunction("getSPItemData("+listObj+") Enter Method");
					try
					{
						//Get content xml for list item with 1 row as rowLimit
						var content = buildQueryContent(listObj.ListName, listObj.CamlQuery, '', 1, null);
						//Ajax call to lists.asmx webservice
						innerPost(listObj.SiteURL+ 'lists.asmx', 'http://schemas.microsoft.com/sharepoint/soap/GetListItems', content, function(data){
							//Make sure data is returned from caml query
							if($('z\\:row', data).get(0) != null)
							{
								//get all result rows
								var SPItem = $('z\\:row', data).get(0).attributes;
								var SPItemName = '';
								$.loginfo("SPItems count:" + SPItem.length);
								$(SPItem).log(null, 4);
								//loop through attributes	
								for (i=0; i<SPItem.length; i++)
								{
									//Set new objects of type jPoint.SPLC["ListName"][SPItemName]
									SPItemName = SPItem[i].name.replace(/ows_/i, "").replace(/_x0020_/g, "");
									listObj[SPItemName]=SPItem[i].value;
									//Add to entry into Items array for display purposes
						            jPointObj.SPLC.Items.push(listObj.ListName.toUpperCase() + "." + SPItemName);
								}	
								//For easy access to SP field count returned from getSPItem call
								jPointObj.SPLC.FieldCount= SPItem.length;
							}
						});
					}
					catch(err)
					{
						$.log("getSPItemData Error:" + err);			
					}
					$.logfunction("getSPItemData() Exit Method");
				}
				/*
				 * name: getSPItems
				 * purpose: fills jpoint.SPLC["ListName"] object with values for all SPList items with specific CAML query
				 * visibility: private
				 * input: listObject (jPoint.SPLC["ListName"] object) , rowLimit (int)
				 * return: data populated in jPoint.SPLC["ListName"] object
				 */
				function getSPItems(listObj, rowLimit)
				{
					$.logfunction("getSPItems("+listObj+", "+rowLimit+") Enter Method");
					try
					{
						//Get content xml for list items with input CAML Query and rowLimit
						var content = buildQueryContent(listObj.ListName, listObj.CamlQuery, listObj.ViewFields, rowLimit, listObj.pagingInfo);
						$.loginfo(content);
						//Ajax call to lists.asmx webservice			
						innerPost(listObj.SiteURL + 'lists.asmx', 'http://schemas.microsoft.com/sharepoint/soap/GetListItems', content, function(data){
							//Get all ajax response rows
							var responseData=$('z\\:row', data);
							//Save jQuery data into jpoint.SPLC["ListName"] object
							listObj.JQueryData=responseData;
							//Add functionality to jpoint.SPLC["ListName"] for drawing jquery data for visual display
							listObj.drawTable=drawTablefromJQueryResponse;
							//Make sure data is returned from caml query
							if($('z\\:row', data).get(0) != null)
							{
								var SPItem = $('z\\:row', data).get(0).attributes;
								var SPItemName = '';
								$.loginfo("SPItem count:" + SPItem.length);
								//loop through attributes
								for (i=0; i<SPItem.length; i++)
								{
									SPItemName = SPItem[i].name.replace(/ows_/i, "").replace(/_x0020_/g, "");
									//Add to entry into Items array for display purposes
									jPointObj.SPLC.Items.push(listObj.ListName.toUpperCase() + "." + SPItemName);
								}	
								//For easy access to SP field count returned from getSPItem call
								jPointObj.SPLC.FieldCount= SPItem.length;
							}
				
						});
					}
					catch(err)
					{
						$.log("getSPItems Error:" + err);
				
					}
					$.logfunction("getSPItems() Exit Method");
				}
				/*
				 * name: getSPViewItems
				 * purpose: fills jpoint.SPLC["ListName"] object with values for all SPList items with specific CAML query which is produced from SPView
				 * visibility: private
				 * input: listObject (jPoint.SPLC["ListName"] object)
				 * return: data populated in jPoint.SPLC["ListName"] object
				 */
				function getSPViewItems(listObj)
				{
					$.logfunction("getSPViewItems("+listObj+") Enter Method");
					try
					{
						//First make a call to get all views
						var content = '<GetViewCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/"><listName>' + listObj.ListName+ '</listName></GetViewCollection>';
						$.loginfo(content);
						innerPost(listObj.SiteURL + 'views.asmx', 'http://schemas.microsoft.com/sharepoint/soap/GetViewCollection', content, function(data){
							//If view name is not passed in then call default view
							if(listObj.ViewName.length == 0)
							{
								listObj.ViewName = "All Items";
							}
							//call particular view from collection of Sharepoint list views
							var ViewNameObj = $(data).find("View[DisplayName='" + listObj.ViewName + "']");
							if(ViewNameObj.attr("Name") != null)
							{
								var ViewName = ViewNameObj.attr("Name"); //TO DO: if statement to check if viewnameobj is null
								content = "<GetView xmlns='http://schemas.microsoft.com/sharepoint/soap/'><listName>" + listObj.ListName + "</listName><viewName>" + ViewName + "</viewName></GetView>";
								$.loginfo(content);
								innerPost(listObj.SiteURL + 'views.asmx', 'http://schemas.microsoft.com/sharepoint/soap/GetView', content, function(data2){
									//Get View node content
									var sQuery = $(data2).find('View').get(0).xml;
									var QueryIndex = sQuery.indexOf("Query") - 1;
									sQuery = sQuery.substr(QueryIndex, sQuery.length - QueryIndex);
									sQuery = sQuery.replace('</View>', '');
									listObj.CamlQuery = sQuery;
									$.loginfo("Call SPList with CAML:" + sQuery);
									//Now that we have CAML query call get list webservice
									getSPItems(listObj, 0)
								});
							}
							else
							{
								alert("'" + listObj.ViewName + "' view does not exist in '" + listObj.ListName + "' list.");
							}
				
						});
					}
					catch(err)
					{
						$.log("getSPItem Error:" + err);
				
					}
					$.logfunction("getSPViewItems() Exit Method");
				}
				/*
				 * name: buildModifyContent
				 * purpose: builds xml soap to be sent for add/update webservice
				 * visibility: private
				 * input: listName (string), data (JSON object)
				 * return: xml schema
				 */
				 function buildModifyContent(listName, data)
				 {
				 	$.logfunction("buildModifyContent("+listName+", "+data+") Enter Method");
				 	var result = new Array();
				 	try
					{
						result.push('<UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">');
						result.push('<listName>' + listName + '</listName>');
						result.push('<updates><Batch OnError="Continue" xmlns="">');
						for(var i = 0; i < data.length; i++) 
						{
							var id = 0;
							if(data[i].id != null)	
						 	{
						 		id=data[i].id;
						 	}
							if (id < 1) //Add item
							{
								result.push('<Method ID="1" Cmd="New">');
							}
						   	else //Update item 
						   	{
								result.push('<Method ID="1" Cmd="Update">');
							  	result.push('<Field Name="ID">' + id + '</Field>');
						   	}
							//Populate fields with values
							var row = data[i];
							$.each(row, function(field, value){
							 if(field.toLowerCase() != 'id')
							 {
								 result.push('<Field Name="');
								 result.push(field);
								 result.push('"><![CDATA[');
								 result.push(value);
								 result.push(']]></Field>');
							 }
							});
						
							result.push('</Method>');
						}
						result.push('</Batch></updates></UpdateListItems>');
					}
					catch(err)
					{
					  $.log("buildModifyContent Error:" + err);
					}
					var resultOutput = result.join("");
					$.loginfo("Result:" + resultOutput);
					$.logfunction("buildModifyContent() Exit Method");
					return resultOutput;
				}
				/*
				 * name: innerPost
				 * purpose: ajax post to sharepoint, for internal use, sync mode
				 * input: web service url (string), "SOAPAction" http header (string), post content (xml), ajax on Success function (function pointer)
				 * visibility: private
				 * return: void
				 */
				function innerPost(wsUrl, actionHeader, wsBody, processFunc){
					try
					{
						$.logfunction("innerPost("+wsUrl+", "+actionHeader+", "+wsBody+", "+processFunc+") Enter Method");
						//Creating new empty Array
						var content = new Array();
						//Adding xml SOAP sturcture components
						content.push("<?xml version='1.0' encoding='utf-8'?>");
						content.push("<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
						content.push("<soap:Body>");
						content.push(wsBody);
						content.push("</soap:Body>");
						content.push("</soap:Envelope>");
						//Calling webservice
						$.ajax({
							async:false,
							type:"POST",
							url: wsUrl,
							contentType:"text/xml; charset=utf-8",
							processData:false,
							data:content.join(""),
							dataType:"xml",
							beforeSend:function(req){
								req.setRequestHeader("X-Vermeer-Content-Type", "text/xml; charset=utf-8");              
								req.setRequestHeader('SOAPAction', actionHeader);
							},
							success:processFunc//Here we call processFunc with response from ajax call
							,
					  	error:
							//In case there was problem reaching webservice we log error
					   		function(XMLHttpRequest, textStatus, errorThrown)
					   		{
								$.log("(Ajax error: "+ textStatus +", " + XMLHttpRequest.statusText+ ")");
					   		}
						});
					}
					catch(err)
					{
						$.log("innerPost Error:" + err);			
					}
					$.logfunction("innerPost Exit Method");
				}
				/*
				 * name: buildQueryContent
				 * purpose: build xml query content, for internal use
				 * input: name of the list (string), CAML query (string), array of the field names (internal name), number of items to query (int), which page to query (int)
				 * visibility: private
				 * return: xml request input for web service call
				 */
				function buildQueryContent(listName, query, viewFields, rowLimit, pagingInfo)
				{
					$.logfunction("buildQueryContent("+listName+", "+query+", "+viewFields+", "+rowLimit+", "+pagingInfo+") Enter Method");
					var result = new Array();
					try
					{	
						//Add GetListItems and list name wrapper
						result.push('<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">');
						result.push('<listName>' + listName + '</listName>');
						if(query.toLowerCase().indexOf('<query') >= 0)//If query already exists from calling view first
						{
							query = query.replace('<Query>', '<query><Query xmlns="">');
							query = query.replace('</Query>', '</Query></query>');
							query = query.replace('<ViewFields>','<viewFields><ViewFields xmlns="">');
							query = query.replace('</ViewFields>','</ViewFields></viewFields>');
							query = query.replace('<QueryOptions>','<queryOptions><QueryOptions xmlns="">');
							query = query.replace('</QueryOptions>','</QueryOptions></queryOptions>');
							query = query.replace('<RowLimit', '<rowLimit');
							query = query.replace('</RowLimit>', '</rowLimit>');
							result.push(query);
						}
						else //Build query
						{
							//Set up query
							if(query != null && query != '')
							{
								result.push('<query><Query xmlns="">');
								result.push(query);
								result.push('</Query></query>');
							}
							//Populate optional view fields
							if(viewFields != null && viewFields.length > -1)
							{
								result.push('<viewFields><ViewFields xmlns="">');
								$.each(viewFields, function(idx, field){
									result.push('<FieldRef Name="' + field + '"/>');
								});
								result.push('</ViewFields></viewFields>');
							}
							//Populate optional row limit count
							if(rowLimit != undefined && rowLimit != null && rowLimit > 0)
								result.push('<rowLimit>' + rowLimit + '</rowLimit>');
							else
							    result.push('<rowLimit>100000</rowLimit>');
							//Set up query options	    
							result.push('<queryOptions><QueryOptions xmlns=""><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>');
							if(pagingInfo != undefined && pagingInfo != null && pagingInfo != '')
								result.push('<Paging ListItemCollectionPositionNext="' + pagingInfo.replace(/&/g, '&amp;') + '" />');
							result.push('</QueryOptions></queryOptions>');
						}	
						result.push('</GetListItems>');
						
					}
					catch(err)
					{
						$.log("buildQueryContent Error:" + err);			
					}
					var returnResult = result.join("");
					$.loginfo("Result:" + returnResult);
					$.logfunction("buildQueryContent Exit Method");
					return returnResult;
				}
				/*
				 * name: drawTablefromJQueryResponse
				 * purpose: display results from jQuery response in either table or div form
				 * input: data (jQuery object), names (array of strings), tableid (object)
				 * visibility: private
				 * return: void
				 */
				function drawTablefromJQueryResponse(data, names, tableid)
				{
					$.logfunction("drawTablefromJQueryResponse("+data+", "+names+", "+tableid+") Enter Method");
					try
					{
					var jData = new Array();
					var rowData;
					var testattr= null;
					$.each(data, function(idx, itemData){
						var SPItem =  $(itemData).get(0).attributes;
						var SPItemName = '';
						rowData = {};		
						$.loginfo("SPItem count:" + SPItem.length);
						for (i=0; i<SPItem.length; i++)
						{
							SPItemName = SPItem[i].name.replace(/ows_/i, "").replace(/_x0020_/g, "").toUpperCase();
							
							$.each(names, function(index, value)
							{
								if(SPItemName == value.toUpperCase())
								{
									var indexValue = escape(SPItem[i].value.replace(/[\r\n]/g,""));
									$.loginfo("rowData "+ value + ":" + indexValue);
									//Add name:value pair to jSON object
									rowData[value] = indexValue;
								}
							});
							
						}
						//Add jSON object to json Array
						jData.push(rowData);
						rowData = null;	
					});
					
					$(document).ready(function(){
					var rootNode = $('#' + tableid + '');	
					$.loginfo("Rendering:" + rootNode.get(0).tagName.toUpperCase());
					//Supports root node of type div or table	
				    switch(rootNode.get(0).tagName.toUpperCase())
						{
							case 'DIV':
								   rootNode.databindDiv(jData);
								break;
							case 'TABLE':
									rootNode.databindTable(jData);
								break;
						}
						});
					}
					catch(err)
					{
						$.log("Error in drawTablefromJQueryResponse" + err);
					}
				}
				$.logfunction("drawTablefromJQueryResponse Exit Method");
				//Return SPList object
				return spObj;
			}
			catch(err)
			{
				$.log("setSPObject Error:" + err);
			}
			$.logfunction("setSPObject Exit Method");
		}
		/*
		 * name: buildDeleteContent
		 * purpose: delete SPItem from a specified list
		 * input: listName (string), id (int)
		 * visibility: private
		 * return: void
		 */
		function buildDeleteContent(listName, id)
		{
			var result = new Array();
			try
			{
				result.push('<UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">');
				result.push('<listName>' + listName + '</listName>');
				result.push('<updates><Batch OnError="Continue" xmlns="">');
				result.push('<Method ID="1" Cmd="Delete">');
				result.push('<Field Name="ID">' + id + '</Field>');
				result.push('</Method>');
				result.push('</Batch></updates></UpdateListItems>');
			}
			catch(err)
			{
				$.log("Error in drawTablefromJQueryResponse" + err);
			}

			var resultOutput = result.join("");
			$.loginfo("Result:" + resultOutput);
			$.logfunction("buildModifyContent() Exit Method");
			return resultOutput;
		}
		//end Private functions ----
		
		//Declare Methods
		this.Form.readForm=readForm;
		this.Form.saveForm=saveForm;
		this.Form.deleteForm=deleteForm;
		this.Form.autoSave=autoSave;
		this.Form.mode=getFormMode;
		this.Form.getItem=getFormItem;
		this.Form.getItemNames=getFormItemNames;
		this.Form.clearForm=clearForm;
		this.SPLC.getItemNames=getSPItemNames;
		this.SPLC.setSPObject=setSPObject;

		
	}
	catch(err)
	{
		$.log("jPointObject Error:" + err);
	}
	$.logfunction("jPoint() Exit Constructor");
}


 
